package com.wsl.mybatiscustomframe.session;

import com.wsl.mybatiscustomframe.execute.Executor;
import com.wsl.mybatiscustomframe.pojo.Configuration;
import com.wsl.mybatiscustomframe.pojo.MappedStatement;

import java.util.List;

/**
 * packageName com.wsl.mybatiscustomframe.session  DefaultSqlSession
 *
 * @author victor
 * @version JDK 8
 * @date 2024/7/11
 * @description TODO
 */
public class DefaultSqlSession implements SqlSession{
    private Configuration configuration;
    private Executor executor;

    public DefaultSqlSession(Configuration configuration, Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    // user.selectList 1 tom user
    @Override
    public <E> List<E> selectList(String statementId, Object params) throws
            Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        // 将查询操作委派给底层的执行器
        List<E> list = executor.query(configuration,mappedStatement,params);
        executor.close();
        return list;
    }



    @Override
    public <T> T selectOne(String statementId, Object params) throws Exception {
        List<Object> list = this.selectList(statementId, params);
        executor.close();
        if(list.size() == 1){
            return (T) list.get(0);
        }else if(list.size() > 1){
            throw new RuntimeException("返回结果过多");
        }else {
            return null;
        }
    }
}
